/**
 * Created by 55456 on 2016/4/11.
 */
var request = require("../instances/request");
var appConfig = require("../configs/appConfig");
var utilx = require("../lib/util");

//request = request.set("Content-type","application/x-www-form-urlencoded");
var baseUrl = "http://openapi.xg.qq.com/push";
var access_id = appConfig.access_id;
var timestamp;
var secret_key = appConfig.secret_key;

var parseSign = function(method,url,params){
    var parsedParams = "";
    var sign = "";
    var _params = {};
    var KeyArr = Object.keys(params).sort();
    for(var x in KeyArr){
        _params[KeyArr[x]] = params[KeyArr[x]];
    }
    // delete _params.sign;
    for(var y in _params){
        parsedParams += (y+"="+_params[y]);
    }
    sign += method.toUpperCase();
    sign += url;
    sign += parsedParams;
    sign += secret_key;
    console.log(sign);
    return utilx.md5(sign);
};

var PushToAndroid = (account,title,content) => {
    var url = baseUrl + "/single_account";
    var message_type = 2;
    var expire_time = 60 * 60 *24;
    var environment = 0;
    var message = {
        "title" : title,
        "content" : content
    };
    var params = {
        access_id : access_id,
        timestamps : Math.round(new Date().getTime()/1000),
        message:message,
        message_type:message_type,
        expire_time:expire_time,
        environment:environment
    };
    params.sign = parseSign("post",url,params);
    return request
            .post(url)
            .set("Content-type","application/x-www-form-urlencoded")
            .send(params);
};